package com.txsj.scan.activity.allocationapply;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.greendao.GoodsInfoDao;
import com.txsj.scan.R;
import com.txsj.scan.activity.AllocationActivity;
import com.txsj.scan.activity.BindLabelActivity;
import com.txsj.scan.adapter.WarehouseDetailAdapter;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.AllocationApplyDetailsBean;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.EventAllocationBean;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.presenter.WareHousePresenter;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.view.IWarehouseDetailView;
import com.txsj.scan.widget.TSnackbarView;
import com.txsj.scan.widget.TitleBarView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class AllocationEpcActivity extends BaseActivity<WareHousePresenter> implements IWarehouseDetailView, View.OnClickListener {


    private TextView goods_count, label_count, tv_allocation, tv_inventory;
    private RecyclerView recyclerView;
    private WarehouseDetailAdapter adapter;
    private TitleBarView mTitle;
    private WarehouseBean warehouseBean;
    private List<EpcInfo> epcList;//未合并相同的标签
    private List<GoodsInfo> goodsList;//未合并的商品列表
    private int itemPosition = -1;
    AllocationApplyDetailsBean detailsBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ware_house);
        this.epcList = new ArrayList<>();
        this.goodsList = new ArrayList<>();
        initView();
        initData();
    }

    private void initData() {
        EventBus.getDefault().register(this);
        String data = getIntent().getStringExtra("source");
        warehouseBean = new Gson().fromJson(data, WarehouseBean.class);
        if (null == warehouseBean) return;
        detailsBean = GsonFactory.parseJsonWithGson(getIntent().getStringExtra("detailsBean"), AllocationApplyDetailsBean.class);

        //表明出库仓库与商品现有仓库是同一个仓库  则该调拨申请的标签不做审核
        if (warehouseBean.getWarehouse_id() == detailsBean.getInto_warehouse_id()) {
            tv_allocation.setVisibility(View.INVISIBLE);
        }
        mTitle.setCenterText(warehouseBean.getWarehouse_name());
        //将传过来的epc信息归类到相应的商品中（为合并相同的商品）
        setGoodsInfoList();
        //去重，没办法找不到为什么
        combineTempList();
        //设置商品种类和商品数量
        setGoodsTypeAndCount();
        //对对应仓库下的商品数据进行缓存
        presenter.getGoodsList(warehouseBean);

    }

    /**
     * 去重
     */
    private void combineTempList() {
        for (GoodsInfo goodsInfo : goodsList) {//遍历整个商品列表
            List<EpcInfo> tempList = new ArrayList<>();//创建零时变量集合
            for (EpcInfo epc : goodsInfo.getEpcList()) {//遍历每个商品下的标签集合
                boolean isHas = false;//标识
                for (EpcInfo temp : tempList) {//遍历零时集合
                    if (temp.getStrEpc().equals(epc.getStrEpc())) {//如果零时集合存在该标签，则不再添加
                        isHas = true;
                        break;
                    }
                }
                if (!isHas) {//如果不存在该标签，添加上
                    tempList.add(epc);
                }
            }
            goodsInfo.setEpcList(tempList);//将去完重复的标签集合重新赋值给商品
        }

        adapter.setData(goodsList);
    }

    /**
     * 第一步将标签赋到商品中，还未合并
     */
    private void setGoodsInfoList() {
        if (null == warehouseBean.getEpcList() || warehouseBean.getEpcList().size() == 0) return;
        for (EpcInfo epcInfo : warehouseBean.getEpcList()) {
            if (epcInfo.getOrder_id() <= 0) {
                epcList.add(epcInfo);
            }
        }
        for (EpcInfo epcInfo : epcList) {

            List<GoodsInfo> goodsList = GreenDaoUtils.getmDaoSession().getGoodsInfoDao().queryBuilder()
                    .where(GoodsInfoDao.Properties.Goods_id.eq(epcInfo.getGoods_id()),
                            GoodsInfoDao.Properties.Warehouse_id.eq(warehouseBean.getWarehouse_id()))
                    .list();
            if (null != goodsList && goodsList.size() > 0) {
                GoodsInfo goods = goodsList.get(0);
                boolean isHas = false;
                int position = -1;
                for (int i = 0; i < this.goodsList.size(); i++) {
                    if (this.goodsList.get(i).getGoods_id() == goods.getGoods_id()) {
                        isHas = true;
                        position = i;
                        break;
                    }
                }
                if (!isHas) {
                    if (null == goods.getEpcList()) goods.setEpcList(new ArrayList<EpcInfo>());
                    goods.getEpcList().add(epcInfo);
                    this.goodsList.add(goods);
                } else {
                    this.goodsList.get(position).getEpcList().add(epcInfo);
                }
            }
        }

    }

    private void initView() {
        this.mTitle = (TitleBarView) findViewById(R.id.mTitle);
        goods_count = (TextView) findViewById(R.id.goods_count);
        label_count = (TextView) findViewById(R.id.label_count);
        tv_allocation = (TextView) findViewById(R.id.tv_allocation);
        tv_allocation.setText("确认调拨");
        tv_inventory = (TextView) findViewById(R.id.tv_inventory);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        tv_inventory.setVisibility(View.GONE);

        tv_allocation.setOnClickListener(this);
        tv_inventory.setOnClickListener(this);
        adapter = new WarehouseDetailAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        adapter.setListener(new WarehouseDetailAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //todo 改进后的展示状态
                if (goodsList.size() == 0 || goodsList.size() < position) return;
                itemPosition = position;
                Intent intent = new Intent(AllocationEpcActivity.this, BindLabelActivity.class);
                intent.putExtra("data", new Gson().toJson(goodsList.get(position)));
                startActivityForResult(intent, 101);
            }

            @Override
            public void onDelete(int position) {
                //TODO 改进后展示 删除本地商品
                goodsList.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 设置商品种类数量及标签数量
     */
    public void setGoodsTypeAndCount() {
        // 标签数量
        label_count.setText(epcList.size() + "");
        //商品数量
        goods_count.setText(goodsList.size() + "");
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_allocation:
                if (goodsList.size() == 0) {
                    showErrorMsg("商品不能为空");
                    return;
                }
                Intent intent = new Intent(AllocationEpcActivity.this, AllocationCheckStatusActivity.class);
                intent.putExtra("data", new Gson().toJson(goodsList));
                intent.putExtra("detailsBean", new Gson().toJson(detailsBean));
                intent.putExtra("isEpc", true);
                startActivity(intent);
                break;
        }
    }


    @Override
    protected WareHousePresenter providePresenter() {
        return presenter = new WareHousePresenter(this);
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public void showErrorMsg(String msg) {
        new TSnackbarView(this.mTitle, msg);
    }

    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    public void onSuccess() {
        hideLoading();

        /**
         * 由于epcInfoList刚传进来要和GoodsInfoDao进行对比，所以在第一次进入的时候GoodsInfoDao为空
         *  所以在缓存结束后再进行对标筛选，
         */
        goodsList.clear();
        epcList.clear();
        //将传过来的epc信息归类到相应的商品中（为合并相同的商品）
        setGoodsInfoList();
        //去重，没办法找不到为什么
        combineTempList();
        //设置商品种类和商品数量
        setGoodsTypeAndCount();
    }


    @Override
    public void onError(String msg) {
        hideLoading();
        showErrorMsg(msg);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            String json = data.getStringExtra("epcData");
            GoodsInfo info = new Gson().fromJson(json, GoodsInfo.class);
            if (info != null) {
                if (info.getEpcList() == null || info.getEpcList().size() == 0) {
                    goodsList.remove(itemPosition);
                } else {
                    goodsList.set(itemPosition, info);
                    adapter.setData(goodsList);
                }
                epcList.clear();
                for (int i = 0; i < goodsList.size(); i++) {
                    epcList.addAll(goodsList.get(i).getEpcList());
                }
                setGoodsTypeAndCount();
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(EventAllocationBean message) {
        if (message.isRefresh()) {
            this.finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
